/**
 * Created by XianTao on 2015/5/18
 * <p>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package com.taotao.chisha.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.taotao.chisha.entity.Meal;
import com.taotao.chisha.entity.MealLog;

import java.sql.SQLException;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "ChiSha.db";
    private static final int DATABASE_VERSION = 1;

    private Dao<Meal, Integer> mealDao;
    private Dao<MealLog, Integer> mealLogDao;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, Meal.class);
            TableUtils.createTable(connectionSource, MealLog.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, Meal.class, true);
            TableUtils.dropTable(connectionSource, MealLog.class, true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        onCreate(sqLiteDatabase, connectionSource);
    }

    public Dao<Meal, Integer> getMealDao() throws SQLException {
        if (mealDao == null) {
            mealDao = getDao(Meal.class);
        }
        return mealDao;
    }

    public Dao<MealLog, Integer> getMealLogDao() throws SQLException {
        if (mealLogDao == null) {
            mealLogDao = getDao(MealLog.class);
        }
        return mealLogDao;
    }
}
